package cn.iocoder.an.module.business.controller.admin.drawconfig;

import cn.iocoder.an.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.an.module.business.controller.admin.equipmentkeeptype.vo.EquipmentKeepTypeImportExcelVO;
import cn.iocoder.an.module.business.controller.admin.equipmentmanage.vo.ImportRespVO;
import cn.iocoder.an.module.business.dal.mysql.drawconfig.DrawConfigMapper;
import cn.iocoder.an.module.business.enums.MaintenanceStatusEnum;
import cn.iocoder.an.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.an.module.system.service.user.AdminUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.v3.oas.annotations.Parameters;
import org.springframework.web.bind.annotation.*;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import jakarta.validation.constraints.*;
import jakarta.validation.*;
import jakarta.servlet.http.*;
import java.util.*;
import java.io.IOException;

import cn.iocoder.an.framework.common.pojo.PageParam;
import cn.iocoder.an.framework.common.pojo.PageResult;
import cn.iocoder.an.framework.common.pojo.CommonResult;
import cn.iocoder.an.framework.common.util.object.BeanUtils;

import static cn.iocoder.an.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.an.framework.common.pojo.CommonResult.success;

import cn.iocoder.an.framework.excel.core.util.ExcelUtils;

import cn.iocoder.an.framework.apilog.core.annotation.ApiAccessLog;
import static cn.iocoder.an.framework.apilog.core.enums.OperateTypeEnum.*;

import cn.iocoder.an.module.business.controller.admin.drawconfig.vo.*;
import cn.iocoder.an.module.business.dal.dataobject.drawconfig.DrawConfigDO;
import cn.iocoder.an.module.business.service.drawconfig.DrawConfigService;
import org.springframework.web.multipart.MultipartFile;

@Tag(name = "管理后台 - 图号配置")
@RestController
@RequestMapping("/business/draw-config")
@Validated
public class DrawConfigController {

    @Resource
    private DrawConfigService drawConfigService;

    @Resource
    private DrawConfigMapper drawConfigMapper;

    @Resource
    private AdminUserService adminUserService;

    @PostMapping("/create")
    @Operation(summary = "创建图号配置")
    @PreAuthorize("@ss.hasPermission('business:draw-config:create')")
    public CommonResult<Long> createDrawConfig(@Valid @RequestBody DrawConfigSaveReqVO createReqVO) {
        return success(drawConfigService.createDrawConfig(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新图号配置")
    @PreAuthorize("@ss.hasPermission('business:draw-config:update')")
    public CommonResult<Boolean> updateDrawConfig(@Valid @RequestBody DrawConfigSaveReqVO updateReqVO) {
        drawConfigService.updateDrawConfig(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除图号配置")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('business:draw-config:delete')")
    public CommonResult<Boolean> deleteDrawConfig(@RequestParam("id") Long id) {
        drawConfigService.deleteDrawConfig(id);
        return success(true);
    }

    @DeleteMapping("/delete-list")
    @Parameter(name = "ids", description = "编号", required = true)
    @Operation(summary = "批量删除图号配置")
                @PreAuthorize("@ss.hasPermission('business:draw-config:delete')")
    public CommonResult<Boolean> deleteDrawConfigList(@RequestParam("ids") List<Long> ids) {
        drawConfigService.deleteDrawConfigListByIds(ids);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得图号配置")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('business:draw-config:query')")
    public CommonResult<DrawConfigRespVO> getDrawConfig(@RequestParam("id") Long id) {
        DrawConfigDO drawConfig = drawConfigService.getDrawConfig(id);
        return success(BeanUtils.toBean(drawConfig, DrawConfigRespVO.class));
    }

    @GetMapping("/getDrawConfigOne")
    @Operation(summary = "获得图号配置")
    public CommonResult<DrawConfigRespVO> getDrawConfigOne() {
        LambdaQueryWrapper<DrawConfigDO> queryWrapper = new LambdaQueryWrapper<DrawConfigDO>();
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        AdminUserDO user = adminUserService.getUser(loginUserId);
        if (user == null) {//管理员切换租户无法查询到
            return null;
        } else {
            String userName = user.getUsername();
            queryWrapper.eq(DrawConfigDO::getCustomerAccount, userName);
            DrawConfigDO first = drawConfigMapper.selectList().getFirst();
            return success(BeanUtils.toBean(first, DrawConfigRespVO.class));
        }
    }


    @GetMapping("/page")
    @Operation(summary = "获得图号配置分页")
    @PreAuthorize("@ss.hasPermission('business:draw-config:query')")
    public CommonResult<PageResult<DrawConfigRespVO>> getDrawConfigPage(@Valid DrawConfigPageReqVO pageReqVO) {
        PageResult<DrawConfigDO> pageResult = drawConfigService.getDrawConfigPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, DrawConfigRespVO.class));
    }


    @GetMapping("/listQuery")
    @Operation(summary = "获得图号配置分页")
    public CommonResult<List<DrawConfigRespVO>> listQuery(@Valid DrawConfigPageReqVO pageReqVO) {
        List<DrawConfigDO> pageResult = drawConfigService.getDrawConfigListQuery(pageReqVO);
        return success(BeanUtils.toBean(pageResult, DrawConfigRespVO.class));
    }


    @GetMapping("/list")
    @Operation(summary = "获得图号配置")
    public CommonResult<List<DrawConfigRespVO>> getDrawConfigList(@Valid DrawConfigPageReqVO pageReqVO) {
        List<DrawConfigDO> pageResult = drawConfigService.getDrawConfigList(pageReqVO);
        return success(BeanUtils.toBean(pageResult, DrawConfigRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出图号配置 Excel")
    @PreAuthorize("@ss.hasPermission('business:draw-config:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportDrawConfigExcel(@Valid DrawConfigPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<DrawConfigDO> list = drawConfigService.getDrawConfigPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "图号配置.xlsx", "数据", DrawConfigRespVO.class,
                        BeanUtils.toBean(list, DrawConfigRespVO.class));
    }


    @GetMapping("/get-import-template")
    @Operation(summary = "导入模板")
    public void importTemplate(HttpServletResponse response) throws IOException {
        // 手动创建导出 demo
        List<DrawConfigImportVo> list = Arrays.asList(
                DrawConfigImportVo.builder().customerAccount("NCJL").customerName("江铃股份")
                        .storeLocation("南昌").storeName("南昌中联物流").drawingNumber("RS1-9461-BA").productName("废气进气管").build(),
                DrawConfigImportVo.builder().customerAccount("QTGL").customerName("钱塘吉利")
                        .storeLocation("杭州").storeName("钱塘富日").drawingNumber("6608045241").productName("空调高低压管总成").build(),
                DrawConfigImportVo.builder().customerAccount("HPXP").customerName("黄埔小鹏")
                        .storeLocation("广州").storeName("广州黄埔").drawingNumber("8125002EA1-00-04").productName("压缩机吸气管").build()
        );
        // 输出
        ExcelUtils.write(response, "导入模板.xlsx", "列表", DrawConfigImportVo.class, list);
    }


    @PostMapping("/import")
    @Operation(summary = "导入")
    @Parameters({
            @Parameter(name = "file", description = "Excel 文件", required = true),
            @Parameter(name = "updateSupport", description = "是否支持更新，默认为 false", example = "true")
    })
    public CommonResult<ImportRespVO> importExcel(@RequestParam("file") MultipartFile file,
                                                  @RequestParam(value = "updateSupport", required = false, defaultValue = "false") Boolean updateSupport) throws Exception {
        List<DrawConfigImportVo> list = ExcelUtils.read(file, DrawConfigImportVo.class);
        return success(drawConfigService.importList(list, updateSupport));
    }


}